from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from .models import Restaurant, Order, MenuItem, OrderItem, CartItem
from .forms import OrderForm, RatingForm
import json
import time
from django.urls import reverse
from .alipay import get_alipay_url, verify_alipay_notification

def restaurant_list(request):
    restaurants = Restaurant.objects.all()
    return render(request, 'order/restaurant_list.html', {'restaurants': restaurants})

@login_required
def restaurant_detail(request, restaurant_id):
    restaurant = get_object_or_404(Restaurant, pk=restaurant_id)
    if request.method == 'POST':
        form = RatingForm(request.POST)
        if form.is_valid():
            rating = form.cleaned_data['rating']
            # 更新餐厅评分
            restaurant.rating = rating
            restaurant.save()
            return redirect('restaurant_detail', restaurant_id=restaurant.id)
    else:
        form = RatingForm()

    return render(request, 'order/restaurant_detail.html', {'restaurant': restaurant, 'form': form})

@login_required
def create_order(request, restaurant_id):
    restaurant = get_object_or_404(Restaurant, id=restaurant_id)
    # 获取餐厅的所有可用菜品
    menu_items = MenuItem.objects.filter(restaurant=restaurant, is_available=True).order_by('name')
    
    # 添加调试信息
    print(f"Restaurant ID: {restaurant_id}")
    print(f"Restaurant: {restaurant}")
    print(f"Menu Items Count: {menu_items.count()}")
    for item in menu_items:
        print(f"Menu Item: {item.name} - ￥{item.price}")
    
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            order = form.save(commit=False)
            order.user = request.user
            order.restaurant = restaurant
            order.total_price = 0  # 初始总价为0，会在添加菜品时更新
            order.save()
            
            messages.success(request, '订单已创建，请添加菜品')
            return redirect('order:menu_items', restaurant_id=restaurant.id)
    else:
        form = OrderForm()
    
    context = {
        'form': form,
        'restaurant': restaurant,
        'menu_items': menu_items,  # 添加菜品列表到上下文
    }
    print(f"Context menu_items count: {len(context['menu_items'])}")
    
    return render(request, 'order/create_order.html', context)

@csrf_exempt
def alipay_notify(request):
    """支付宝异步通知"""
    if request.method == 'POST':
        try:
            data = request.POST.dict()
            signature = data.pop("sign")
            
            # 验证签名
            if verify_alipay_notification(data, signature):
                out_trade_no = data.get('out_trade_no', '')
                trade_status = data.get('trade_status', '')
                
                if trade_status == 'TRADE_SUCCESS':
                    order_id = out_trade_no.split('_')[1]  # 从订单号中提取ID
                    try:
                        order = Order.objects.get(id=order_id)
                        if order.status == '待支付':
                            order.status = '已支付'
                            order.trade_no = data.get('trade_no', '')
                            order.save()
                            return HttpResponse('success')
                    except Order.DoesNotExist:
                        pass
            
            return HttpResponse('fail')
        except Exception as e:
            return HttpResponse('fail')
    
    return HttpResponse('fail')

@login_required
def alipay_return(request):
    """支付宝同步通知"""
    try:
        data = request.GET.dict()
        signature = data.pop("sign")
        
        # 验证签名
        if verify_alipay_notification(data, signature):
            # 获取订单号
            out_trade_no = data.get('out_trade_no', '')
            order_id = out_trade_no.split('_')[1]  # 从订单号中提取ID
            
            try:
                order = Order.objects.get(id=order_id)
                if order.status == '待支付':
                    order.status = '已支付'
                    order.trade_no = data.get('trade_no', '')
                    order.save()
                    messages.success(request, '支付成功！')
                else:
                    messages.info(request, '订单已处理')
            except Order.DoesNotExist:
                messages.error(request, '订单不存在')
        else:
            messages.error(request, '支付验证失败')
    except Exception as e:
        messages.error(request, f'处理支付回调时发生错误: {str(e)}')
    
    return redirect('order:order_list')

@login_required
def order_list(request):
    """订单列表"""
    orders = Order.objects.filter(user=request.user).order_by('-created_at')
    return render(request, 'order/order_list.html', {'orders': orders})

@login_required
def cancel_order(request, order_id):
    order = get_object_or_404(Order, id=order_id, user=request.user)
    if order.status == '待支付':
        order.status = '已取消'
        order.save()
        messages.success(request, '订单已成功取消')
    else:
        messages.error(request, '只能取消待支付的订单')
    return redirect('order:order_list')

@login_required
def order_pay(request, order_id):
    order = get_object_or_404(Order, id=order_id, user=request.user)
    
    if order.status != '待支付':
        messages.error(request, '该订单状态不允许支付')
        return redirect('order:order_list')
    
    try:
        # 生成订单标题
        subject = f"外卖订单-{order.restaurant.name}-{order.food_name}"
        
        # 生成订单号（添加时间戳避免重复）
        order_number = f"order_{order.id}_{int(time.time())}"
        
        # 获取支付URL
        pay_url = get_alipay_url(
            order_number=order_number,
            total_amount=float(order.total_price),
            subject=subject
        )
        
        return redirect(pay_url)
        
    except Exception as e:
        messages.error(request, f'生成支付链接时发生错误: {str(e)}')
        return redirect('order:order_list')

@csrf_exempt
def alipay_notify_new(request):
    """支付宝异步通知处理"""
    if request.method == 'POST':
        try:
            data = request.POST.dict()
            signature = data.pop("sign")

            alipay = AliPay(
                appid=settings.ALIPAY_APPID,
                app_notify_url=None,
                app_private_key_string=settings.ALIPAY_PRIVATE_KEY,
                alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY,
                sign_type="RSA2",
                debug=settings.ALIPAY_DEBUG
            )

            success = alipay.verify(data, signature)
            if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                order_id = int(data["out_trade_no"])
                trade_no = data["trade_no"]
                
                try:
                    order = Order.objects.get(id=order_id)
                    if order.status == '待支付':
                        order.status = '已支付'
                        order.trade_no = trade_no
                        order.save()
                        return HttpResponse('success')
                except Order.DoesNotExist:
                    return HttpResponse('fail')
        except Exception as e:
            return HttpResponse('fail')
    
    return HttpResponse('fail')

@login_required
def alipay_return_new(request):
    """支付宝同步返回处理"""
    data = request.GET.dict()
    signature = data.pop("sign")

    alipay = AliPay(
        appid=settings.ALIPAY_APPID,
        app_notify_url=None,
        app_private_key_string=settings.ALIPAY_PRIVATE_KEY,
        alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY,
        sign_type="RSA2",
        debug=settings.ALIPAY_DEBUG
    )

    success = alipay.verify(data, signature)
    if success:
        order_id = int(data["out_trade_no"])
        try:
            order = Order.objects.get(id=order_id, user=request.user)
            if order.status == '待支付':
                order.status = '已支付'
                order.trade_no = data.get("trade_no")
                order.save()
                messages.success(request, '支付成功！')
            else:
                messages.info(request, '订单已经支付')
        except Order.DoesNotExist:
            messages.error(request, '订单不存在')
    else:
        messages.error(request, '支付验证失败')
    
    return redirect('order:order_list')

@login_required
def menu_items(request, restaurant_id):
    restaurant = get_object_or_404(Restaurant, id=restaurant_id)
    menu_items = MenuItem.objects.filter(restaurant=restaurant, is_available=True).order_by('category', 'name')
    
    # 按类别分组菜品
    categorized_items = {}
    for item in menu_items:
        if item.category not in categorized_items:
            categorized_items[item.category] = []
        categorized_items[item.category].append(item)
    
    context = {
        'restaurant': restaurant,
        'categorized_items': categorized_items,
    }
    return render(request, 'order/menu_items.html', context)

@login_required
def add_to_cart(request):
    if request.method == 'POST':
        menu_item_id = request.POST.get('menu_item')
        quantity = int(request.POST.get('quantity', 1))
        restaurant_id = request.POST.get('restaurant_id')
        
        menu_item = get_object_or_404(MenuItem, id=menu_item_id)
        
        # 创建或获取购物车项
        cart_item, created = CartItem.objects.get_or_create(
            user=request.user,
            menu_item=menu_item,
            defaults={'quantity': quantity}
        )
        
        if not created:
            cart_item.quantity += quantity
            cart_item.save()
        
        messages.success(request, f'已将 {menu_item.name} x{quantity} 添加到购物车')
        return redirect('order:create_order', restaurant_id=restaurant_id)
    
    return redirect('order:restaurant_list')